<!-- 登录 -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    //调api检差是否登录
    const redirectUrl = new URLSearchParams(window.location.search).get('redirect');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/api/auth/checkToken', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send();
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        const res = JSON.parse(xhr.responseText);
        if (res.statusCode === 200) {
          // 已登录
          window.location.href = redirectUrl + '?token=' + res.data.access_token + '&expired_at=' + res
            .data
            .expiryDate;
        } else {
          // 未登录
        }
      }
    }

  </script>
  <!-- 登录 -->
  <form>
    <input type="text" name="username" placeholder="请输入用户名">
    <input type="password" name="password" placeholder="请输入密码">
    <input type="submit" value="登录">
  </form>
  <script>
    // 1. 获取登录按钮
    const loginBtn = document.querySelector('input[type="submit"]');
    // 2. 给登录按钮绑定点击事件
    loginBtn.addEventListener('click', function (e) {
      // 3. 阻止默认事件
      e.preventDefault();
      // 4. 获取用户名和密码
      const username = document.querySelector('input[name="username"]').value;
      const password = document.querySelector('input[name="password"]').value;
      // 5. 发送请求
      const xhr = new XMLHttpRequest();
      const redirectUrl = new URLSearchParams(window.location.search).get('redirect');
      xhr.open('POST', `/api/auth/login?redirect=${redirectUrl}`, true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(JSON.stringify({
        username,
        password
      }));
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 201) {
          const res = JSON.parse(xhr.responseText);
          if (res.statusCode === 200) {
            // 登录成功
            window.location.href = res.data.redirectUrl + '?token=' + res.data.access_token + '&expired_at=' + res
              .data
              .expiryDate;
          } else {
            // 登录失败

          }
        }
      }
    });

  </script>

</body>

</html>
